package com.hertz.iris.view;

import java.io.IOException;

import javax.inject.Inject;

import android.accounts.AccountManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import com.github.kevinsawicki.wishlist.Toaster;
import com.hertz.iris.IrisServiceProvider;
import com.hertz.iris.R;
import com.hertz.iris.authenticator.OpenIdTokenProvider;
import com.hertz.iris.core.MatchAlarmService;
import com.hertz.iris.pojo.User;
import com.hertz.iris.receiver.ConnectivyBroadcastReceiver;
import com.hertz.iris.ui.IrisFragmentActivity;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.Strings;
import com.hertz.iris.util.Utils;

public class IndexActivity extends IrisFragmentActivity {

	@InjectView(R.id.sel_account_bt)
	Button b1;
	@InjectView(R.id.guest_bt)
	Button b2;
	@InjectView(R.id.index_text)
	TextView indexText;
	@InjectView(R.id.ok_btn_progress)
	ProgressBar okBtnProgress;
	@InjectView(R.id.sel_account_btn_progress)
	ProgressBar selAccountBtnProgress;
	@InjectView(R.id.networkBanner)
	LinearLayout networkBanner;
	
	@Inject protected IrisServiceProvider serviceProvider;
	@Inject protected MatchAlarmService matchAlarmService;
	@Inject OpenIdTokenProvider openIdTokenProvider;
//	@Inject protected TriggerService triggerService;
	private String openIdToken;
	
	private BroadcastReceiver connectivyBroadcastReceiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index);
		ButterKnife.inject(this);
		//check network
		if(Utils.checkNetwork(getBaseContext())){
        	networkBanner.setVisibility(View.GONE);
        }else{
        	networkBanner.setVisibility(View.VISIBLE);
        }
        connectivyBroadcastReceiver = new ConnectivyBroadcastReceiver(networkBanner);
        IntentFilter filter = new IntentFilter();  
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
        registerReceiver(connectivyBroadcastReceiver, filter);
        
		openIdToken = getOpenIdToken();
		if(!Strings.isBlank(openIdToken)){
			gotoMain();
		}
	}

	@Override
    public void onActivityResult(int requestCode,int resultCode,Intent intent){
		String authKey = intent == null ? "" : intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
		String authType = intent == null ? "" : intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
		if(!Strings.isBlank(authKey)){
			selAccountBtnProgress.setVisibility(View.VISIBLE);
			Runnable runnable = new OpenIdRunnable(authKey, authType);
			new Thread(runnable).start();
		}else{
			Toaster.showLong(this, Constants.ToastMessage.UN_SEL_ACCOUNT);
		}
	}
	
	@OnClick(R.id.sel_account_bt) void selAccount(){
		Intent intent = AccountManager.newChooseAccountIntent(null, null, null,
				true, null, null, null, null);
		startActivityForResult(intent, 1);
	}
	
	@OnClick(R.id.guest_bt) void gotoAsGuest(){
		WifiManager m_wm = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
		String m_wlanMacAdd = m_wm.getConnectionInfo().getMacAddress();
		okBtnProgress.setVisibility(View.VISIBLE);
		Runnable runnable = new OpenIdRunnable(m_wlanMacAdd, Constants.Auth.IRIS_ACCOUNT_TYPE);
		new Thread(runnable).start();
	}
	
	private class OpenIdRunnable implements Runnable{
		private String token;
		private String userName;
		private String site;
		public OpenIdRunnable(String userName ,String site){
			this.userName = userName;
			this.site = site;
		}
		
		@Override
		public void run() {
			Message message = new Message();  
            User user = null;
            try {
            	
				user = serviceProvider.getService(IndexActivity.this).getUser(userName, site);
				if(user != null){
	            	message.what = 1;
	            	openIdTokenProvider.setOpenIdToken(user.getOpenIdToken(), user.getSsoUserName(), user.getSsoSite(),IndexActivity.this);
	            	boolean syncResult = matchAlarmService.syncData(Constants.DEFAULT_SYNC_TIME_DAYS, IndexActivity.this);
	            	if(!syncResult){
						message.what = 0;
					}
	            }
			}catch (HttpRequestException hre){
				hre.printStackTrace();
				message.what = -1;
			} catch (IOException ioe){
				ioe.printStackTrace();
				message.what = 0;
			} 
            
            IndexActivity.this.openIdHandler.sendMessage(message);
		}
	}
	
	private Handler openIdHandler = new Handler(){  
        
        public void handleMessage(Message msg) {  
        	okBtnProgress.setVisibility(View.GONE);
            switch (msg.what) {  
            case -1:
            	Toaster.showShort(IndexActivity.this, Constants.ToastMessage.NETWORK_ERROR);
            	okBtnProgress.setVisibility(View.GONE);
            	selAccountBtnProgress.setVisibility(View.GONE);
            	break;
            case 1:  
            	gotoMain();
                break;
            case 0:
            	Toaster.showShort(IndexActivity.this, Constants.ToastMessage.LOGIN_ERROR);
            	okBtnProgress.setVisibility(View.GONE);
            	selAccountBtnProgress.setVisibility(View.GONE);
            }  
        };  
    };  
	
	private void gotoMain(){
//		triggerService.matchAlarmAlertTrigger(System.currentTimeMillis() + Constants.DEFAULT_INTERVAL);
//		MatchAlarm ma = new MatchAlarm();
//		ma.setMid(1);
//		matchAlarmService.createNotication(ma, this);
		Intent gotoMain = new Intent(this, MainActivity.class);
		startActivity(gotoMain);
		finish();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(connectivyBroadcastReceiver);
	}  
}
